<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { EmailTaskVO } from '#/api/contact/task/email/model';

import { useRouter } from 'vue-router';

import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { getVxePopupContainer } from '@vben/utils';

import { Modal, Popconfirm, Space, Tag } from 'ant-design-vue';

import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import {
  emailTaskExport,
  emailTaskInfo,
  emailTaskPage,
  emailTaskRemove,
} from '#/api/contact/task/email';
import { DetailsModal } from '#/components/modal';
import { commonDownloadExcel } from '#/utils/file/download';
import emailPreviewModal from '#/views/config/template/email/components/email-preview-modal.vue';

import { columns, detailsSchema, querySchema } from './data';
import emailTaskDrawer from './email-task-drawer.vue';

const router = useRouter();

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  // arrayToStringFields: 'favoriteIds',
  schema: querySchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  fieldMappingTime: [
    [
      'sendTime',
      ['sendTimeStart', 'sendTimeEnd'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // reserve: true,
    // trigger: 'row',
  },
  columns,
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await emailTaskPage({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  id: 'email-task-list-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

// 详情
const [EmailTaskDetailsModal, detailsModalApi] = useVbenModal({
  connectedComponent: DetailsModal,
});

function handlePreview(record: EmailTaskVO) {
  detailsModalApi.setData(record);
  detailsModalApi.open();
}

// 预览邮件
const [EmailPreviewModal, emailPreviewModalApi] = useVbenModal({
  connectedComponent: emailPreviewModal,
});

async function handlePreviewFile(row: EmailTaskVO) {
  if (row.templateUrl) {
    window.open(row.templateUrl);
  } else if (row.templateOssId) {
    emailPreviewModalApi.setData({ ossId: row.templateOssId });
    emailPreviewModalApi.open();
  } else if (row.templateId) {
    emailPreviewModalApi.setData({ id: row.templateId });
    emailPreviewModalApi.open();
  }
}

// 查看总结

function handleReport(row: EmailTaskVO) {
  router.push({
    path: '/contact/statistics/email',
    query: { taskId: row.id },
  });
}

const [EmailTaskDrawer, emailTaskDrawerApi] = useVbenDrawer({
  connectedComponent: emailTaskDrawer,
});

function handleAdd() {
  emailTaskDrawerApi.setData({});
  emailTaskDrawerApi.open();
}

// async function handleEdit(row: EmailTaskVO) {
//   emailTaskDrawerApi.setData({ id: row.id });
//   emailTaskDrawerApi.open();
// }

async function handleDelete(row: EmailTaskVO) {
  await emailTaskRemove(row.id);
  await tableApi.query();
}

function handleMultiDelete() {
  const rows = tableApi.grid.getCheckboxRecords();
  const ids = rows.map((row: EmailTaskVO) => row.id);
  Modal.confirm({
    title: '提示',
    okType: 'danger',
    content: `确认删除选中的${ids.length}条记录吗？`,
    onOk: async () => {
      await emailTaskRemove(ids);
      await tableApi.query();
    },
  });
}

function handleDownloadExcel() {
  commonDownloadExcel(
    emailTaskExport,
    '邮件联络任务数据',
    tableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="邮件任务列表">
      <template #toolbar-tools>
        <Space>
          <a-button
            v-access:code="['email:task:export']"
            @click="handleDownloadExcel"
          >
            {{ $t('pages.common.export') }}
          </a-button>
          <a-button
            :disabled="!vxeCheckboxChecked(tableApi)"
            danger
            type="primary"
            v-access:code="['email:task:remove']"
            @click="handleMultiDelete"
          >
            {{ $t('pages.common.delete') }}
          </a-button>
          <a-button
            type="primary"
            v-access:code="['email:task:add']"
            @click="handleAdd"
          >
            {{ $t('pages.common.add') }}
          </a-button>
        </Space>
      </template>
      <template #favorites="{ row }">
        <div
          v-if="row.favorites?.length > 0"
          class="flex flex-wrap justify-center gap-1"
        >
          <Tag v-for="favorite in row.favorites" :key="favorite.id">
            {{ favorite.name }}
          </Tag>
        </div>
      </template>
      <template #sendCount="{ row }">
        <span>{{ row.sendCount || 0 }} / {{ row.sendTotal || 0 }}</span>
      </template>
      <template #action="{ row }">
        <Space>
          <ghost-button
            v-access:code="['email:task:query']"
            @click.stop="handlePreview(row)"
          >
            {{ $t('pages.common.info') }}
          </ghost-button>
          <ghost-button @click.stop="handlePreviewFile(row)">预览</ghost-button>
          <ghost-button @click="handleReport(row)">总结</ghost-button>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <ghost-button
              danger
              v-access:code="['email:task:remove']"
              @click.stop=""
            >
              {{ $t('pages.common.delete') }}
            </ghost-button>
          </Popconfirm>
        </Space>
      </template>
    </BasicTable>
    <EmailTaskDrawer @reload="tableApi.query()" />
    <EmailTaskDetailsModal
      :width="700"
      :columns="detailsSchema()"
      :api="emailTaskInfo"
    >
      <template #favorites="{ info }">
        <div v-if="info.favorites?.length > 0" class="flex flex-wrap gap-1">
          <Tag v-for="favorite in info.favorites" :key="favorite.id">
            {{ favorite.name }}
          </Tag>
        </div>
      </template>
    </EmailTaskDetailsModal>
    <EmailPreviewModal />
  </Page>
</template>
